package com.eee.machine.utils.youzan;

import com.eee.machine.common.TokenBean;
import com.eee.machine.configuration.StoreConfig;
import com.youzan.open.sdk.api.APIFactory;
import com.youzan.open.sdk.client.oauth.model.OAuthToken;
import com.youzan.open.sdk.client.oauth.types.AuthorizationCode;
import com.youzan.open.sdk.client.oauth.types.RefreshToken;
import com.youzan.open.sdk.util.http.DefaultHttpClient;
import com.youzan.open.sdk.util.http.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.connection.ReactiveListCommands;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.util.Calendar;
import java.util.Date;

@Component
public class TokenUtil {

    @Autowired
    private TokenBean tokenBean;
    private static volatile OAuthToken token = null;
    private static StoreConfig storeConfig;
    private static DefaultHttpClient httpClient = new DefaultHttpClient();
    public static StoreConfig getStoreConfig() {
        return storeConfig;
    }

    @Autowired
    public void setStoreConfig(StoreConfig storeConfig) {
        TokenUtil.storeConfig = storeConfig;
    }

    public static OAuthToken getToken(){
        if(token == null){
            synchronized (TokenUtil.class){
                if(token == null){
                    AuthorizationCode authorizationCode = new AuthorizationCode(storeConfig.getClientId(), storeConfig.getClientSecret(), storeConfig.getRedirectUrl(), storeConfig.getState(), storeConfig.getCode());
                    token = authorizationCode.getToken();
                }
            }
        }
        return token;
    }

    public String getAccessToken(){
        if(tokenBean.getExpireTime().after(new Date())){
            return tokenBean.getAccessToken();
        }else{
            String refreshToken = tokenBean.getRefreshToken();
            RefreshToken newRefreshToken = new RefreshToken(storeConfig.getClientId(), storeConfig.getClientSecret(), refreshToken);
            OAuthToken token = newRefreshToken.getToken();
            Integer expiresIn = token.getExpiresIn();
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.SECOND, expiresIn);
            tokenBean.setExpireTime(instance.getTime());
            tokenBean.setAccessToken(token.getAccessToken());
            tokenBean.setRefreshToken(token.getRefreshToken());
            return tokenBean.getAccessToken();
        }
    }
}
